package com.crm.common.utils;

import cn.hutool.json.JSONUtil;

import java.util.HashMap;

public class ThreadLocalUtil {
    // 提供ThreadLocal 对象
    private static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal<>();

    // 获取存储值
    public static <T> T get() {
        return (T) THREAD_LOCAL.get();
    }

    // 存储值
    public static void set(Object value) {
        THREAD_LOCAL.set(value);
    }

    // 清除THREAD_LOCAL 防止内存泄漏
    public static void remove() {
        THREAD_LOCAL.remove();
    }


    /**
     * 获取当前用户ID
     *
     * @return
     */
    public static Long getUserId() {
        Object object = ThreadLocalUtil.get();

        if (object == null) {
            return 1L;
        }
        HashMap map = JSONUtil.toBean(JSONUtil.toJsonStr(object), HashMap.class);

        return Long.valueOf(map.get("userId") + "");
    }

    public static String getUserName() {
        Object object = ThreadLocalUtil.get();
        if (object == null) {
            return "admin";
        }
        HashMap map = JSONUtil.toBean(JSONUtil.toJsonStr(object), HashMap.class);

        return map.get("userName") + "";
    }
}

